package com.fac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fac.constant.CommonConstant;
import com.fac.constant.ExceptionConstant;
import com.fac.constant.UserType;
import com.fac.dto.UsersDTO;
import com.fac.dto.UsersLoginDTO;
import com.fac.dto.UsersPageQueryDTO;
import com.fac.dto.UsersRegisterDTO;
import com.fac.entity.Users;
import com.fac.exception.AccountNotFoundException;
import com.fac.exception.BusinessException;
import com.fac.mapper.UsersMapper;
import com.fac.result.PageResult;
import com.fac.service.UsersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public Users login(UsersLoginDTO usersLoginDTO) {
        final String username = usersLoginDTO.getUsername();
        String password = usersLoginDTO.getPassword();

        // 根据用户名查询用户
        LambdaQueryWrapper<Users> lqw = new LambdaQueryWrapper<>();
        // 显式指定了需要查询的字段，包括 password 字段
        lqw.select(Users::getUserId, Users::getUsername, Users::getPassword, 
                  Users::getUserType, Users::getStatus, Users::getRealName)
           .eq(Users::getUsername, username);
        final Users users = usersMapper.selectOne(lqw);

        if (users == null) {
            throw new AccountNotFoundException(ExceptionConstant.ERROR_ACCOUNT_NOT_FOUND);
        }

        // 验证密码
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!encryptedPassword.equals(users.getPassword())) {
            throw new AccountNotFoundException(ExceptionConstant.ERROR_PASSWORD);
        }

        // 账户是否启用
        if (users.getStatus().equals(CommonConstant.STATUS_DISABLE)) {
            throw new AccountNotFoundException(ExceptionConstant.ERROR_ACCOUNT_LOCKED);
        }

        // 更新最后登录时间
        Users updateUser = new Users();
        updateUser.setUserId(users.getUserId());
        updateUser.setLastLoginTime(LocalDateTime.now());
        usersMapper.updateById(updateUser);

        return users;
    }

    @Override
    public void save(UsersDTO usersDTO) {
        final Users users = new Users();
        // 将dto对象转换为entity对象
        BeanUtils.copyProperties(usersDTO, users);
        // 账户默认启用
        users.setStatus(CommonConstant.STATUS_ENABLE);
        // 默认密码123456,存入数据库前 进行md5加密
        users.setPassword(DigestUtils.md5DigestAsHex(CommonConstant.DEFAULT_PASSWORD.getBytes()));

        usersMapper.insert(users);
    }

    @Override
    public PageResult pageQuery(UsersPageQueryDTO usersPageQueryDTO) {
        // 利用MybatisPlus进行分页查询
        final LambdaQueryWrapper<Users> usersLambdaQueryWrapper = Wrappers.lambdaQuery();

        // 添加过滤条件
        // 1. 用户姓名模糊查询
        if (usersPageQueryDTO.getKeyword() != null && !usersPageQueryDTO.getKeyword().isEmpty()) {
            usersLambdaQueryWrapper.like(Users::getUsername, usersPageQueryDTO.getKeyword());
        }
        // 2. 用户类型查询
        if (usersPageQueryDTO.getUserType() != null) {
            usersLambdaQueryWrapper.eq(Users::getUserType, usersPageQueryDTO.getUserType());
        }

        final Page<Users> userPage = new Page<>(usersPageQueryDTO.getPage(), usersPageQueryDTO.getSize());
        final Page<Users> selectPage = usersMapper.selectPage(userPage, usersLambdaQueryWrapper);

        return new PageResult(selectPage.getTotal(), selectPage.getRecords());
    }

    @Override
    public Users getById(Long userId) {
        return usersMapper.selectById(userId);
    }

    @Override
    public void updateByUserId(UsersDTO usersDTO) {
        // 1. 检查用户是否存在
        Users existingUser = usersMapper.selectById(usersDTO.getUserId());
        if (existingUser == null) {
            throw new BusinessException("用户不存在");
        }

        // 2. 如果修改了用户名，检查新用户名是否已存在
        if (!existingUser.getUsername().equals(usersDTO.getUsername())) {
            LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Users::getUsername, usersDTO.getUsername())
                    .ne(Users::getUserId, usersDTO.getUserId());
            if (usersMapper.selectCount(queryWrapper) > 0) {
                throw new BusinessException(ExceptionConstant.ERROR_USERNAME_EXISTS);
            }
        }

        // 3. 如果修改了手机号，检查新手机号是否已存在
        if (!existingUser.getMobile().equals(usersDTO.getMobile())) {
            LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Users::getMobile, usersDTO.getMobile())
                    .ne(Users::getUserId, usersDTO.getUserId());
            if (usersMapper.selectCount(queryWrapper) > 0) {
                throw new BusinessException(ExceptionConstant.ERROR_PHONE_EXISTS);
            }
        }

        // 4. 更新用户信息
        Users users = new Users();
        BeanUtils.copyProperties(usersDTO, users);
        
        // 5. 执行更新操作
        int rows = usersMapper.updateById(users);
        if (rows == 0) {
            throw new BusinessException("更新用户信息失败");
        }
    }

    @Override
    public void delete(Long userId) {
        usersMapper.deleteById(userId);
    }

    @Override
    public void register(UsersRegisterDTO usersRegisterDTO) {
        // 1. 校验两次密码是否一致
        if (!usersRegisterDTO.getPassword().equals(usersRegisterDTO.getConfirmPassword())) {
            throw new BusinessException(ExceptionConstant.ERROR_PASSWORD_NOT_MATCH);
        }

        // 2. 校验用户名是否已存在
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getUsername, usersRegisterDTO.getUsername());
        if (usersMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException(ExceptionConstant.ERROR_USERNAME_EXISTS);
        }

        // 3. 校验手机号是否已存在
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getMobile, usersRegisterDTO.getMobile());
        if (usersMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException(ExceptionConstant.ERROR_PHONE_EXISTS);
        }

        // 4. 创建用户实体
        Users users = new Users();
        BeanUtils.copyProperties(usersRegisterDTO, users);

        // 5. 密码加密
        users.setPassword(DigestUtils.md5DigestAsHex(users.getPassword().getBytes()));

        // 6. 设置默认值
        // 默认启用
        users.setStatus(CommonConstant.STATUS_ENABLE);
        // 默认为工人
        users.setUserType(UserType.WORKER);

        // 7. 保存用户
        usersMapper.insert(users);
    }

}
